import { Space, Button, message, } from 'antd';
import ProCard from '@ant-design/pro-card';
import React, { useState, useRef, useEffect } from 'react';
import { getDvaApp, history, } from 'umi';
import ProForm, {
    ProFormText,
    ProFormSelect,
} from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import $utils from '@/utils/utils';
import { segmentCreate, segmentUpdate, getBySegment } from '@/services/num';
import { getExpressData, } from '@/services/company';

const Detail: React.FC = () => {

    // 解决无法调用dispatch
    const dispatch = getDvaApp()._store.dispatch;
    const formRef = useRef<ProFormInstance>();
    const [cur_id, setCur_id] = useState<string>();
    const [numDetail, setNumDetail] = useState<any>();
    const [expressList, setExpressList] = useState<API.Select[]>([]);



    const l_state: any = history.location.state;
    if (!cur_id && !l_state) {
        history.push('/BasicConfig/Num');
    }

    const id: string = l_state?.data?.id || '';
    //  同path更新,只更新state时，通过id重新请求数据
    if ((l_state && id) && (!cur_id || cur_id !== id)) {
        console.log('state', l_state);
        setCur_id(id);
    } else if (l_state && !id && cur_id !== id) {
        setCur_id('');
    }

    const isCreate: boolean = l_state?.status === 'create';
    const isUpdate: boolean = l_state?.status === 'update';


    // 快递公司列表
    useEffect(() => {
        const getOptions = async () => {
            let result = $utils.getStorage('express_options');
            !result && (result = await getExpressData());

            setExpressList(result);
        };
        getOptions();
        if (!cur_id) {
            setNumDetail(undefined);
            formRef && formRef.current?.resetFields();
        }
        else {
            const num_data = {
                segment: l_state?.data?.segment,
                expressId: l_state?.data?.expressName,
            };
            setNumDetail(num_data);
            formRef && formRef.current?.resetFields();
            return;
        }
    }, [cur_id]);

    return (
        <PageContainer>
            {(isCreate || numDetail) && <ProCard style={{ marginTop: 8 }} gutter={8} >
                <ProForm
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 16 }}
                    layout={"horizontal"}
                    formRef={formRef}
                    initialValues={isCreate ? undefined : numDetail}
                    onFinish={async (values) => {
                        if (typeof values.expressId === "string") {
                            values.expressId = expressList.find(item => item.label === values.expressId)?.value;
                        }
                        let params = {
                            segment: values.segment,
                            expressId: values.expressId
                        };
                        const quayle = await getBySegment({ segment: values.segment, });
                        if (quayle.code === 0) {
                            const name = expressList.find(item => item.value === quayle.body.expressId)?.label;
                            return message.warning(`${values.segment}号段已归属${name},无法添加`, 1);
                        }
                        if (isCreate) {
                            params = Object.assign(params, { name: values.name });
                            const msg = await segmentCreate(params);
                            if (msg.code === 0) {
                                message.success('新增成功', 1, () => {
                                    // 设置当前tab对象
                                    $utils.setNewTab(dispatch, { name: '号段管理', path: '/BasicConfig/Num', isTopMenu: true });
                                    history.push('/BasicConfig/Num');
                                });
                            }
                        }
                        else if (isUpdate) {
                            params = Object.assign(params, { id });
                            const msg = await segmentUpdate(params);
                            if (msg.code === 0) {
                                message.success('编辑成功', 1, () => {
                                    // 设置当前tab对象
                                    $utils.setNewTab(dispatch, { name: '号段管理', path: '/BasicConfig/Num', isTopMenu: true });
                                    history.push('/BasicConfig/Num');
                                });
                            }
                        }
                    }}
                    submitter={{
                        render: (props, doms) => {
                            return [
                                <Space style={{ marginLeft: '16.66666667%' }}>
                                    <Button type="primary" htmlType="submit">保存</Button>
                                    <Button onClick={() => {
                                        // 设置当前tab对象
                                        $utils.setNewTab(dispatch, { name: '号段管理', path: '/BasicConfig/Num', isTopMenu: true });
                                        history.push('/BasicConfig/Num');
                                    }}>取消</Button>
                                </Space>
                            ]
                        }
                    }}
                >
                    <ProFormText
                        width={'md'}
                        name="segment"
                        label={'运营号段'}
                        rules={[
                            {
                                required: true,
                                len: 3,
                            },
                            {
                                pattern: new RegExp('^[0-9a-zA-Z_]{1,}$', 'g'),
                                message: '号段只能输入26个字母与0-9的数字组合'
                            }
                        ]}
                    />
                    <ProFormSelect
                        width={'md'}
                        name="expressId"
                        label={'快递公司'}
                        rules={[
                            {
                                required: true,
                                message: '请选择号段归属快递公司'
                            }
                        ]}
                        fieldProps={{
                            showSearch: true,
                            options: expressList,
                        }}
                    />
                </ProForm>
            </ProCard>}
        </PageContainer>
    );
};

export default Detail;
